<?php

/**
 * SvnFile class.
 *
 *
 * @package    lib
 * @subpackage lib_svn
 * @author     Juan Carlos Jarquin (zetta)
 * @author     $LastChangedBy$
 * @version    0.2, SVN: $Id$
 */

class Svn
{
  
  /**
   * @var string
   */
  private $auth = '';
  
  /**
   * Class Constructor
   * @return Svn
   */
  public function Svn()
  {
    $this->auth = $this->analizeAuth();
  }
  
  /**
   * Get the Svn Version
   * @return string
   */
  public function getVersion()
  {
    return $this->exec("svn --version | head -n 1");
  }
  
  public function getFileInformation($url)
  {
    $return = array();
    $info = $this->exec('svn info ' . $url.$this->auth);
    $info = explode("\n", $info);
    foreach ($info as $string)
    {
      @list ($name, $value) = explode(':', $string, 2);
      if (! trim($name))
        continue;
      $return[$this->getKeyName($name)] = trim($value);
    }
    
    $return['raw'] = $this->getUpDir($return['url']) . '/' . $return['name'];
    $return['last-changed-date'] = new Date($return['last-changed-date']);
    return $return;
  }
  
  /**
   * Convierte un string a un nombre valido de llave
   * @param string $name
   * @return string
   */
  public function getKeyName($name)
  {
    $name = trim($name);
    $name = strtolower($name);
    $name = str_replace(' ', '-', $name);
    return $name;
  }
  
  public function getUpDir($file)
  {
    $url = parse_url($file);
    $dir = dirname($url['path']);
    return $dir;
  }

  /**
   * Get code
   *
   * @param sring $url
   * @return string
   */
  public function getCode($url)
  {
    return $this->exec('svn cat '.$url.$this->auth);
  }
  
  /**
   * Analize the auth
   * @return string
   */
  private function analizeAuth()
  {
    $auth = '';
    $request = Request::getInstance();
    $user = $request->getServer('PHP_AUTH_USER');
    if($user !== null)
    {
      $pass = $request->getServer('PHP_AUTH_PW');
      $auth = " --username {$user} --password {$pass}";
    }
    return $auth;
  }
  
  /**
   * Execute a command
   * @param string $cmd
   * @return string
   */
  private function exec($cmd)
  {
    $command = getcwd() . '/command.sh ' . $cmd;
    $output = array();
    exec($command, $output);
    
    return implode("\n", $output);
  }

}